package com.atguigu.stgy.common.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import io.minio.errors.InsufficientDataException;
import io.minio.errors.InternalException;
import io.minio.errors.InvalidResponseException;
import io.minio.errors.XmlParserException;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.ErrorResponseException;

import java.io.IOException;
import java.rmi.ServerException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Data
@ConfigurationProperties(prefix = "stgy.minio")
public class MinioConfig {
    private String endpoint;//: http://192.168.123.168:9000
    private String accessKey;//: minioadmin
    private String secretKey;//: minioadmin
    private String bucket;//: stgy

    public static String ENDPOINT;//: http://192.168.123.168:9000
    public static String ACCESS_KEY;//: minioadmin
    public static String SECRET_KEY;//: minioadmin
    public static String BUCKET;//: stgy
    @PostConstruct //jdk注解  标注的方法再当前对象创建后执行
    public void init(){
        ENDPOINT = this.endpoint;
        ACCESS_KEY = this.accessKey;
        SECRET_KEY = this.secretKey;
        BUCKET = this.bucket;
    }

    @Bean
    public MinioClient minioClient() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, io.minio.errors.ServerException, io.minio.errors.ErrorResponseException {
        //初始化minio客户端对象注入到容器中
        MinioClient minioClient = MinioClient.builder().endpoint(MinioConfig.ENDPOINT)
                .credentials(MinioConfig.ACCESS_KEY, MinioConfig.SECRET_KEY)
                .build();
        //初始化minio桶
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(MinioConfig.BUCKET).build());
        if(!exists){
            //如果桶不存在 初始化桶
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(MinioConfig.BUCKET)
                    .build());
            String config = """
            {
                "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                } ],
                "Version" : "2012-10-17"
            }
            """;
            //给字符串的占位符设置 参数值
            config = config.formatted(MinioConfig.BUCKET);
            //配置桶的访问权限： 私有写公共读
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(MinioConfig.BUCKET)
                    .config(config).build());
        }
        return minioClient;
    }
}